package com.softWang.system.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.softWang.common.tenent.aop.TenantIgnore;
import com.softWang.system.controller.vo.systemTenant.*;
import com.softWang.system.mapper.SystemDeptsMapper;
import com.softWang.system.mapper.SystemTenantMenuMapper;
import com.softWang.system.mapper.SystemUsersMapper;
import com.softWang.system.po.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import com.softWang.common.base.BaseServiceMy;
import com.softWang.common.exception.LogicException;
import com.softWang.system.mapper.SystemTenantMapper;

/**
 * <p>
 * 系统管理--租户表 服务实现类
 * </p>
 *
 * @author wang
 * @since 2025-08-28
 */
@Service
public class SystemTenantService extends BaseServiceMy<SystemTenant> {

     @Resource
     private SystemTenantMapper systemTenantMapper;
     @Resource
     private SystemUsersService systemUsersService;
     @Resource
     private SystemDeptsService systemDeptsService;
     @Resource
     private SystemUsersMapper systemUsersMapper;
     @Resource
     private SystemDeptsMapper systemDeptsMapper;

     @Resource
     private SystemTenantMenuMapper systemTenantMenuMapper;
     /**
     * 分页条件查询
     * @param param
     * @return
     */
     @TenantIgnore
     public List<SystemTenantQueryAllResult> queryall(SystemTenantQueryAllParam param){
         param.startPage();
         List<SystemTenantQueryAllResult> results=systemTenantMapper.queryall(param);
         return results;
     }

      /**
      * 插入
      * @param param 数据信息
      * @return id
      */
      @Transactional
      @TenantIgnore
      public Long add(SystemTenantAddParam param) {

          SystemTenant entity = new SystemTenant();
          BeanUtils.copyProperties(param, entity);
          // 验证租户参数信息
          valdationTenant(entity);

          //添加租户表
          entity.setType(SystemTenant.Type.COMMON.getCode());
          systemTenantMapper.insert(entity);

          //添加租户的顶级部门
          SystemDepts dept = new SystemDepts();
          dept.setDname(param.getTname());
          dept.setPid(0L);
          dept.setTenantId(entity.getId());
          systemDeptsService.add(dept);

          //添加租户管理员到用户表
          SystemUsers user = new SystemUsers();
          BeanUtils.copyProperties(param, user);
          user.setTenantId(entity.getId());
          user.setDeptid(dept.getId());
          user.setUname(param.getContactName());
          user.setTel(param.getContactMobile());
          user.setType(SystemUsers.UserType.TENANT_ADMIN.getCode());
          user.setState(SystemUsers.UserState.NORMAL.getCode());
          systemUsersService.add(user);

          return entity.getId();
      }

      /**
      * 修改
      * @param param  数据信息
      * @return
      */
      @TenantIgnore
      @Transactional
      public Long edit(SystemTenantEditParam param) {

         SystemTenant entity = new SystemTenant();
         BeanUtils.copyProperties(param, entity);

         systemTenantMapper.updateById(entity);

         //修改租户管理员信息
         SystemUsers user = systemUsersService.getTenantAdminByTenantId(param.getId());
         user.setUname(param.getContactName());
         user.setTel(param.getContactMobile());
         user.setSex(param.getSex());
         user.setEmail(param.getEmail());
         systemUsersMapper.updateById(user);

         //修改租户的顶级部门名称
         SystemDepts dept = systemDeptsMapper.selectOne(Wrappers.lambdaQuery(SystemDepts.class)
                .eq(SystemDepts::getTenantId, param.getId()).eq(SystemDepts::getPid, 0));

         dept.setDname(param.getTname());

         systemDeptsMapper.updateById(dept);

         return entity.getId();
      }

      /**
      * 获取详情
      * @param id id
      * @return 详情信息
      */
      public SystemTenant getById(Long id) {
           return systemTenantMapper.selectById(id);
      }

      /**
      * 删除
      * @param ids id列表
      * @return void
      */
      @Transactional
      public void del(List<Long> ids) {
          systemTenantMapper.deleteBatchIds(ids);
      }

    private void valdationTenant(SystemTenant param){
        // 验证名称唯一性
        Long num = systemTenantMapper.selectCount(
                new LambdaQueryWrapper<SystemTenant>()
                        .eq(SystemTenant::getTname, param.getTname())
                        .ne(param.getId()!=null,SystemTenant::getId, param.getId()));
        if (num > 0) {
            throw new LogicException("租户名称已存在!");
        }
    }

    /**
     * 初始化租户管理员密码
     * @param id 租户id
     */
    @Transactional
    @TenantIgnore
    public void initPassword(Long id) {
        SystemUsers user = systemUsersService.getTenantAdminByTenantId(id);
        systemUsersService.initPassword(user.getId());
    }

    /**
     * 分配租户菜单
     * @param param 分配菜单参数信息
     */
    @Transactional
    @TenantIgnore
    public void assignMenu(SystemTenantAssignMenuParam param) {
        //删除租户菜单关系
        systemTenantMenuMapper.delete(new LambdaQueryWrapper<SystemTenantMenu>()
                .eq(SystemTenantMenu::getTenantId, param.getId()));
        //插入租户菜单关系
        List<Long> menuIds = param.getMenuIds();
        if(menuIds!= null && menuIds.size() > 0){
            List<SystemTenantMenu> tenantMenus = new ArrayList<>();
            for(Long menuId : menuIds){
                SystemTenantMenu tenantMenu = new SystemTenantMenu();
                tenantMenu.setTenantId(param.getId());
                tenantMenu.setMenuId(menuId);
                tenantMenu.setHalf(0);
                tenantMenus.add(tenantMenu);
            }
            systemTenantMenuMapper.insert(tenantMenus);
        }
        //插入半选租户菜单关系
        List<Long> halfMenuIds = param.getHalfMenuIds();
        if(halfMenuIds!= null && halfMenuIds.size() > 0){
            List<SystemTenantMenu> tenantMenus = new ArrayList<>();
            for(Long menuId : halfMenuIds){
                SystemTenantMenu tenantMenu = new SystemTenantMenu();
                tenantMenu.setTenantId(param.getId());
                tenantMenu.setMenuId(menuId);
                tenantMenu.setHalf(1);
                tenantMenus.add(tenantMenu);
            }
            systemTenantMenuMapper.insert(tenantMenus);
        }
    }


    /**
     * 获取租户菜单
     * @param id 租户id
     * @return 租户菜单信息
     */
    public SystemTenantGetTenantMenuResult getTenantMenu(Long id) {
        SystemTenantGetTenantMenuResult result = new SystemTenantGetTenantMenuResult();
        result.setId(id);
        //获取租户菜单
        List<SystemTenantMenu> tenantMenus = systemTenantMenuMapper.selectList(Wrappers.lambdaQuery(SystemTenantMenu.class)
                .eq(SystemTenantMenu::getTenantId, id)
                .eq(SystemTenantMenu::getHalf,0));
        List<Long> menuIds = new ArrayList<>();
        for(SystemTenantMenu tenantMenu : tenantMenus){
            menuIds.add(tenantMenu.getMenuId());
        }
        result.setMenuIds(menuIds);
        return result;
    }
}
